﻿using System.Collections;
using System.Collections.Generic;
using Const;
using Entitas;
using UnityEngine;

public class ExchangeSystem : ReactiveSystem<GameEntity>
{
    public ExchangeSystem(Contexts context) : base(context.game)
    {
        
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.ComponentsExchange);
    }

    protected override bool Filter(GameEntity entity)
    {
        return entity.hasComponentsExchange&&entity.isComponentsMovable==true
               && (entity.componentsExchange.exchangeState == ExchangeState.START
               || entity.componentsExchange.exchangeState == ExchangeState.EXCHANGE_BACK);
    }

    protected override void Execute(List<GameEntity> entities)
    {
        
        
        
       // Debug.Log(entities.Count);
        if (entities.Count == 2)
        {
           // Debug.Log("Entities.count=2");
            Exchange(entities[0],entities[1]);
        }
    }

    private void Exchange(GameEntity first, GameEntity second)
    {
        var First = first.componentsItemIndex.index;
        var Second = second.componentsItemIndex.index;
        
        first.ReplaceComponentsItemIndex(Second);
        second.ReplaceComponentsItemIndex(First);
        
        setExchangeState(first);
        setExchangeState(second);
    }

    private void setExchangeState(GameEntity entity)
    {
        if (entity.componentsExchange.exchangeState == ExchangeState.START)
        {
            entity.ReplaceComponentsExchange(ExchangeState.EXCHANGE);
        }
        else if (entity.componentsExchange.exchangeState == ExchangeState.EXCHANGE_BACK)
        {
            entity.ReplaceComponentsExchange(ExchangeState.END);
        }
    }
}
